package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client4 {
    private Socket socket;
    public Client4() {

        try {
            System.out.println("正在链接服务器...");
            socket =new Socket("176.15.11.37",8088);//176.15.11.35肖
            System.out.println("一个服务器连上了...");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public void start() {

        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw =new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw =new BufferedWriter(osw);
            PrintWriter pw =new PrintWriter(bw,true);

            InputStream in = socket.getInputStream();
            InputStreamReader isr =new InputStreamReader(in,StandardCharsets.UTF_8);
            BufferedReader br =new BufferedReader(isr);


            Scanner scanner =new Scanner(System.in);
            while(true){
                String line = scanner.nextLine();
                if("exit".equals(line)){
                    break;
                }
                pw.println(line);
                //读取来自服务器发送过来的消息
                line=br.readLine();
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{//关闭流建议写在finally中,网络流的关闭,直接关闭socket就行
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client4 client =new Client4();
        client.start();
    }
}
